package vn.gq.app4vn.doctruyen;

import vn.gq.cd.model.ChapterAdapter;
import vn.gq.cd.model.bean.BookmarkItem;
import vn.gq.cd.model.bean.CategoryItem;
import vn.gq.tym.utils.DialogHelper;
import vn.gq.tym.utils.IDialogHelper;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class BookmarkManager {
	
	public static final String PREF_BOOKMARK = "pref_bookmark";
	public static final String BOOKMARK_KEY = "bookmark";
	private Activity activity;
	
	public BookmarkManager(Activity activity) {
		this.activity = activity;
	}
	
	public void clear() {
		SharedPreferences pref = activity.getSharedPreferences(PREF_BOOKMARK, Context.MODE_PRIVATE);
		pref.edit().clear().commit();
	}
	
	public void save(BookmarkItem item) {
		SharedPreferences pref = activity.getSharedPreferences(PREF_BOOKMARK, Context.MODE_PRIVATE);
		Editor editor = pref.edit();
		editor.putString(BOOKMARK_KEY, item.toJSONObject().toString());
		editor.commit();
	}
	
	public BookmarkItem get() {
		SharedPreferences pref = activity.getSharedPreferences(PREF_BOOKMARK, Context.MODE_PRIVATE);
		BookmarkItem item = new BookmarkItem(pref.getString(BOOKMARK_KEY, new BookmarkItem().toJSONObject().toString()));
		return item;
	}
	
	public int getBookmarkChapterPos() {
		BookmarkItem bm = get();
		return bm.lasPosition;
	}
	
	public void showDialogConfirm() {
		final BookmarkItem bookmark = get();
		try {
			if (!bookmark.catUrl.equals("") && !bookmark.chapterName.equals("")) {
				String message = (!bookmark.catName.equals("")) ? 
					String.format("Nhấn Có để đọc tiếp %s > %s", bookmark.catName, bookmark.chapterName) : 
					String.format("Nhấn Có để đọc tiếp %s", bookmark.chapterName);
					
				DialogHelper.showConfirm(activity, message, new IDialogHelper() {
	
					@Override
					public void onOk() {
						final CategoryItem item = new CategoryItem(bookmark.catUrl, bookmark.catName);
						final ChapterAdapter adapter = new ChapterAdapter(activity, null);
						adapter.load(item.getPath(), new Runnable() {
							
							@Override
							public void run() {
								ReaderActivity.startActivity(activity, item, adapter.getData(), bookmark.chapterPos, bookmark.scrollPosY, true, new OnStartActivityCallBack() {
									
									@Override
									public void onDone(Intent intent) {
										activity.startActivityForResult(intent, 1);
									}
								});
							}
						});
					}
					
					@Override
					public void onCancel() {
					}
					
				}, false);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
